#Code: Produce estimates used to generate Figure 5 in the manuscript. 

library(PowerUpR)
library(ggplot2)
library(tidyverse)

#Initial values 
min_n<-50
max_n<-1000
power<-.8
sample<-(seq(from=min_n, to = max_n, by=1))
datalist = list()  
counta=0
countb=0
r_pre_input<-c(.0, .36, .56, .81)
k_input<-c(0,1,1,1)
length_r_pre_input<-length(r_pre_input)

#Run Loop
for(h in 1:length(r_pre_input)){
  mat1<-matrix(data=NA, nrow=length(sample), ncol=4)
  
  for (i in sample) {
    counta<-counta+1
    mdeobj<-mdes.ira1r1(power=.8, 
                        alpha=.05, 
                        two.tailed=T, 
                        p=.5, 
                        g1=k_input[h], 
                        r21=r_pre_input[h], 
                        n=i)
    mat1[counta,1] <- i 
    mat1[counta,2] <- r_pre_input[h]
    mat1[counta,3] <- h
    mat1[counta,4] <- mdeobj$mdes[,1]
  }  
  counta<-0 
  final<-as_tibble(mat1)  
  final<-final %>% rename(N=V1,r_pre=V2, r_pre_cat=V3, MDES=V4)
  countb<-countb+1
  datalist[[countb]]<-assign(paste0("df",h), final)
  
}

df_final<-bind_rows(datalist)
df_final

df_final$r_pre<-factor(df_final$r_pre, 
                       levels=r_pre_input)
df_final$r_pre_cat<-factor(df_final$r_pre_cat, 
                           levels=c(1,2,3,4),
                           labels=c("Post-only","Pre-post (r = .6)","Pre-post (r = .75)","Pre-post (r = .9)"))

x<-ggplot(df_final, aes(x=N, y=MDES, group=r_pre_cat))
plot1<-x+
  geom_line(aes(color=r_pre_cat), lwd=2.5)+
  scale_color_grey(name="Design")+
  scale_x_continuous(breaks=seq(50, 1000, 50),expand = c(.01,.01))+
  ylab("Minimum Detectable Effect Size")+
  xlab("Total Sample Size")+
  theme_bw()+
  theme(plot.title = element_text(size=18))+
  theme(legend.title=element_text(size=17, face="bold"))+
  theme(legend.position="right")+
  theme(legend.text=element_text(size=17))+
  theme(axis.text=element_text(size=17),
        axis.title=element_text(size=17,face="bold"))

plot1

ggsave(filename="Plot - MDE.tiff",
       device="tiff",
       width=13, 
       height=8, 
       units=c("in"),
       dpi=300)

##Values reported in text 

#N = 100

df_final %>% filter(N==100)

#Sample Size 

#d = .2
df_final %>% filter(MDES<=.2001 | MDES >= 1.999) %>% filter(r_pre==0)
df_final %>% filter(MDES<=.2001 | MDES >= 1.999) %>% filter(r_pre==0.36)
df_final %>% filter(MDES<=.2001 | MDES >= 1.999) %>% filter(r_pre==0.56)
df_final %>% filter(MDES<=.2001 | MDES >= 1.999) %>% filter(r_pre==0.81)

#d = . 5 
df_final %>% filter(MDES<=.5001 | MDES >= 4.999) %>% filter(r_pre==0)
df_final %>% filter(MDES<=.5001 | MDES >= 4.999) %>% filter(r_pre==0.36)
df_final %>% filter(MDES<=.5001 | MDES >= 4.999) %>% filter(r_pre==0.56)
df_final %>% filter(MDES<=.5001 | MDES >= 4.999) %>% filter(r_pre==0.81)

#N=400

df_final %>% filter(N==400)






